/**
 * CORS 配置
 */
const CORS_CONFIG = {
  allowedOrigins: '*', // 允许所有来源，生产环境应限制具体域名
  allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 86400, // 预检请求缓存时间（秒）
};

/**
 * 处理 CORS 预检请求
 */
export function handleOptionsRequest(request: Request): Response {
  const origin = request.headers.get('Origin') || '*';

  return new Response(null, {
    headers: {
      'Access-Control-Allow-Origin': origin,
      'Access-Control-Allow-Methods': CORS_CONFIG.allowedMethods.join(', '),
      'Access-Control-Allow-Headers': CORS_CONFIG.allowedHeaders.join(', '),
      'Access-Control-Max-Age': CORS_CONFIG.maxAge.toString(),
    },
  });
}

/**
 * 添加 CORS 响应头
 */
export function addCorsHeaders(response: Response, request: Request): Response {
  const origin = request.headers.get('Origin') || '*';
  const headers = new Headers(response.headers);

  // 添加 CORS 头
  headers.set('Access-Control-Allow-Origin', origin);
  headers.set('Access-Control-Allow-Credentials', 'true');

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
  });
}